package com.qinglei.recoup.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.exception.RecoupException;
import com.qinglei.recoup.common.utils.DateUtil;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.system.dao.EventLogMapper;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.enums.EventEnum;
import com.qinglei.recoup.system.manager.DictManager;
import com.qinglei.recoup.system.manager.UserManager;
import com.qinglei.recoup.system.pojo.AllEventParam;
import com.qinglei.recoup.system.pojo.BedEventParam;
import com.qinglei.recoup.system.pojo.BedMonitorTimeVO;
import com.qinglei.recoup.system.pojo.EventLogDTO;
import com.qinglei.recoup.system.pojo.EventLogVO;
import com.qinglei.recoup.system.pojo.PageParam;
import com.qinglei.recoup.system.pojo.SearchEventParam;
import com.qinglei.recoup.system.pojo.event.EventLogEvent;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.EventLogService;
import com.qinglei.recoup.system.service.EventService;
import com.qinglei.recoup.system.service.EventWsService;
import com.qinglei.recoup.system.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author syp
 */
@Service
@Slf4j
public class EventLogServiceImpl extends ServiceImpl<EventLogMapper, EventLog> implements EventLogService {

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Resource
    private EventWsService eventWsService;

    @Resource
    private BedService bedService;

    @Resource
    private UserManager userManager;

    @Resource
    private EventService eventService;

    @Resource
    private DictManager dictManager;

    @Autowired
    private SystemConfigService systemConfigService;


    @Override
    public void procEventLog(Integer bedId, Long userId, Long eventId, Integer type, String content, Integer tenantId) {
        EventLogDTO eventData = new EventLogDTO();
        eventData.setBedId(bedId);
        eventData.setUserId(userId);
        eventData.setEventId(eventId);
        eventData.setType(type);
        eventData.setContent(content);
        eventData.setTenantId(tenantId);
        // 发送异步消息
        applicationEventPublisher.publishEvent(new EventLogEvent(eventData));
    }

    @EventListener
    @Async
    public void eventLogEventHandler(EventLogEvent event) throws RecoupException {
        log.debug("eventLogEventHandler, param:{}", event);
        EventLogDTO eventData = event.getEventData();
        EventEnum eventEnum = EventEnum.getByCode(eventData.getType());
        if (eventEnum == null) {
            log.warn("不支持的事件类型: {}", eventData.getType());
            return;
        }
        EventLog eventLog = new EventLog();
        eventLog.setTenantId(eventData.getTenantId());
        switch (eventEnum) {
            case ALARM_OUT_BED:
            case ALARM_FALL_DOWN:
                eventLog = procAlarmEvent(eventData, eventEnum);
                break;
            case SLEEP_STATUS_OUT_BED:
            case SLEEP_STATUS_CLEAR:
            case SLEEP_STATUS_LIGHT:
            case SLEEP_STATUS_DEEP:
            case MONITOR_TIME_START:
            case MONITOR_TIME_END:
            case MONITOR_TIME_ADD:
            case MONITOR_OFFLINE:
            case MONITOR_ONLINE:
            case MONITOR_TIME_DELETE:
                eventLog = procBedCommon(eventData, eventEnum);
                break;
            case MONITOR_SWITCH_ON:
            case MONITOR_SWITCH_OFF:
                eventLog = procMonitorSwitch(eventData, eventEnum);
                break;
            case NURSE_WORK_LOGIN:
            case NURSE_WORK_LOGOUT:
                eventLog = procNurseWork(eventData, eventEnum);
                break;
            case EVENT_PROC_TAKE:
            case EVENT_PROC_PROCESSING:
            case EVENT_PROC_FINISH:
            case EVENT_PROC_UNFINISHED:
            case EVENT_PROC_PROC_MISSED_EVENT:
            case EVENT_PROC_HAPPEN_MISSED_EVENT:
                eventLog = this.procEventProc(eventData, eventEnum);
                break;
            case TOUR_START:
                eventLog.setType(EventEnum.TOUR_START.getCode());
                eventLog.setTypeGroup(EventEnum.TOUR_START.getType());
                eventLog.setContent(String.format(EventEnum.TOUR_START.getContent(), eventData.getContent()));
                eventLog.setCreateTime(LocalDateTime.now());
                this.save(eventLog);
                break;
            case TOUR_END:
                eventLog.setUserId(eventData.getUserId());
                eventLog.setType(EventEnum.TOUR_END.getCode());
                eventLog.setTypeGroup(EventEnum.TOUR_END.getType());
                eventLog.setContent(String.format(EventEnum.TOUR_END.getContent(), getNurseName(eventData.getUserId())));
                eventLog.setCreateTime(LocalDateTime.now());
                this.save(eventLog);
                break;
            case TOUR_UNFINISHED:
                eventLog.setUserId(eventData.getUserId());
                eventLog.setType(EventEnum.TOUR_UNFINISHED.getCode());
                eventLog.setTypeGroup(EventEnum.TOUR_UNFINISHED.getType());
                eventLog.setContent(String.format(EventEnum.TOUR_UNFINISHED.getContent(), getNurseName(eventData.getUserId()), eventData.getContent()));
                eventLog.setCreateTime(LocalDateTime.now());
                this.save(eventLog);
                break;
            default:
                throw new RecoupException("eventLogEventHandler 不支持的事件类型:" + eventEnum);
        }
        // 推送事件
        eventWsService.pushEventMsg(eventLog);
    }

    private EventLog procAlarmEvent(EventLogDTO eventData, EventEnum eventEnum) {
        EventLog eventLog = new EventLog();
        eventLog.setBedId(eventData.getBedId());
        eventLog.setName(getBedName(eventData.getBedId()));
        eventLog.setEventId(eventData.getEventId());
        eventLog.setType(eventEnum.getCode());
        eventLog.setTypeGroup(eventEnum.getType());
        eventLog.setContent(eventEnum.getContent());
        eventLog.setCreateTime(LocalDateTime.now());
        eventLog.setTenantId(eventData.getTenantId());
        this.save(eventLog);
        return eventLog;
    }

    /**
     * 处理时间处理相关消息
     *
     * @param eventData
     * @param eventEnum
     * @return
     */
    private EventLog procEventProc(EventLogDTO eventData, EventEnum eventEnum) {
        Event event = eventService.getById(eventData.getEventId());
        if (event == null) {
            log.warn("procEventProc event not exist,eventData:{}", eventData);
            return null;
        }
        EventLog eventLog = new EventLog();
        eventLog.setTenantId(eventData.getTenantId());
        eventLog.setBedId(eventData.getBedId());
        eventLog.setName(getBedName(eventData.getBedId()));
        eventLog.setEventId(eventData.getEventId());
        eventLog.setCreateTime(LocalDateTime.now());
        String eventName = "离床";
        if (event.getType() != null && event.getType() == Bed.SUB_STATUS_FALL_DOWN) {
            eventName = "跌倒";
        }else if (event.getType() != null && event.getType() == BedHealthState.SUB_STATUS_BREATH_HIGHT){
            eventName = "呼吸过速";
        }else if (event.getType() != null && event.getType() == BedHealthState.SUB_STATUS_BREATH_LOW){
            eventName = "呼吸暂停过久";
        }else if (event.getType() != null && event.getType() == BedHealthState.SUB_STATUS_HEART_HIGHT){
            eventName = "心跳过速";
        }else if (event.getType() != null && event.getType() == BedHealthState.SUB_STATUS_HEART_LOW){
            eventName = "心跳过缓";
        }
        switch (eventEnum) {
            case EVENT_PROC_TAKE:
                eventLog.setUserId(eventData.getUserId());
                eventLog.setType(EventEnum.EVENT_PROC_TAKE.getCode());
                eventLog.setTypeGroup(EventEnum.EVENT_PROC_TAKE.getType());
                eventLog.setContent(String.format(EventEnum.EVENT_PROC_TAKE.getContent(), getNurseName(eventData.getUserId()), eventName));
                break;
            case EVENT_PROC_PROCESSING:
                eventLog.setType(EventEnum.EVENT_PROC_PROCESSING.getCode());
                eventLog.setTypeGroup(EventEnum.EVENT_PROC_PROCESSING.getType());
                eventLog.setContent(EventEnum.EVENT_PROC_PROCESSING.getContent());
                break;
            case EVENT_PROC_FINISH:
                eventLog.setUserId(eventData.getUserId());
                eventLog.setType(EventEnum.EVENT_PROC_FINISH.getCode());
                eventLog.setTypeGroup(EventEnum.EVENT_PROC_FINISH.getType());
                eventLog.setContent(String.format(EventEnum.EVENT_PROC_FINISH.getContent(), getNurseName(eventData.getUserId()), eventName, eventData.getContent()));
                break;
            case EVENT_PROC_UNFINISHED:
                eventLog.setUserId(eventData.getUserId());
                eventLog.setType(EventEnum.EVENT_PROC_UNFINISHED.getCode());
                eventLog.setTypeGroup(EventEnum.EVENT_PROC_UNFINISHED.getType());
                Integer takeEventTimeout = systemConfigService.getTakeEventTimeoutRedisCache(eventData.getTenantId());
                String time = DateUtil.getTimes(takeEventTimeout);
                eventLog.setContent(String.format(EventEnum.EVENT_PROC_UNFINISHED.getContent(), getNurseName(eventData.getUserId()), time, eventName));
                break;
            case EVENT_PROC_PROC_MISSED_EVENT:
                eventLog.setUserId(eventData.getUserId());
                eventLog.setType(EventEnum.EVENT_PROC_PROC_MISSED_EVENT.getCode());
                eventLog.setTypeGroup(EventEnum.EVENT_PROC_PROC_MISSED_EVENT.getType());
                eventLog.setContent(eventData.getContent());
                break;
            case EVENT_PROC_HAPPEN_MISSED_EVENT:
                eventLog.setUserId(eventData.getUserId());
                eventLog.setType(EventEnum.EVENT_PROC_HAPPEN_MISSED_EVENT.getCode());
                eventLog.setTypeGroup(EventEnum.EVENT_PROC_HAPPEN_MISSED_EVENT.getType());
                eventLog.setContent(String.format(EventEnum.EVENT_PROC_HAPPEN_MISSED_EVENT.getContent(), getNurseName(eventData.getUserId()), eventName));
                break;
        }
        this.save(eventLog);
        return eventLog;
    }
//    private EventLog procSleepStatus(EventLogDTO eventData, EventEnum eventEnum) {
//        EventLog eventLog = new EventLog();
//        eventLog.setBedId(eventData.getBedId());
//        eventLog.setName(getBedName(eventData.getBedId()));
//        eventLog.setType(eventEnum.getCode());
//        eventLog.setTypeGroup(eventEnum.getType());
//        eventLog.setContent(eventEnum.getContent());
//        eventLog.setCreateTime(LocalDateTime.now());
//        this.save(eventLog);
//        return eventLog;
//    }

    private EventLog procMonitorSwitch(EventLogDTO eventData, EventEnum eventEnum) {
        EventLog eventLog = new EventLog();
        eventLog.setBedId(eventData.getBedId());
        eventLog.setName(getBedName(eventData.getBedId()));
        eventLog.setType(eventEnum.getCode());
        eventLog.setTypeGroup(eventEnum.getType());
        eventLog.setContent(String.format(eventEnum.getContent(), getNurseName(eventData.getUserId())));
        eventLog.setCreateTime(LocalDateTime.now());
        eventLog.setTenantId(eventData.getTenantId());
        this.save(eventLog);
        return eventLog;
    }

    private EventLog procBedCommon(EventLogDTO eventData, EventEnum eventEnum) {
        EventLog eventLog = new EventLog();
        eventLog.setBedId(eventData.getBedId());
        eventLog.setName(getBedName(eventData.getBedId()));
        eventLog.setType(eventEnum.getCode());
        eventLog.setTypeGroup(eventEnum.getType());
        eventLog.setContent(eventEnum.getContent());
        eventLog.setCreateTime(LocalDateTime.now());
        eventLog.setTenantId(eventData.getTenantId());
        //离床状态不记录日志
        if(eventEnum.getCode()!=EventEnum.SLEEP_STATUS_OUT_BED.getCode()){
            this.save(eventLog);
        }

        return eventLog;
    }

//    private EventLog procMonitorTime(EventLogDTO eventData, EventEnum eventEnum) {
//        EventLog eventLog = new EventLog();
//        eventLog.setBedId(eventData.getBedId());
//        eventLog.setName(getBedName(eventData.getBedId()));
//        eventLog.setType(eventEnum.getCode());
//        eventLog.setTypeGroup(eventEnum.getType());
//        eventLog.setContent(eventEnum.getContent());
//        eventLog.setCreateTime(LocalDateTime.now());
//        this.save(eventLog);
//        return eventLog;
//    }

    private EventLog procNurseWork(EventLogDTO eventData, EventEnum eventEnum) {
        EventLog eventLog = new EventLog();
        eventLog.setUserId(eventData.getUserId());
        eventLog.setType(eventEnum.getCode());
        eventLog.setTypeGroup(eventEnum.getType());
        eventLog.setNurseName(getNurseName(eventData.getUserId()));
        eventLog.setContent(String.format(eventEnum.getContent(), eventLog.getNurseName()));
        eventLog.setCreateTime(LocalDateTime.now());
        eventLog.setTenantId(eventData.getTenantId());
        this.save(eventLog);
        return eventLog;
    }

//    private EventLog procTakeEvent(EventLogDTO eventData) {
//        EventLog eventLog = new EventLog();
//        eventLog.setBedId(eventData.getBedId());
//        eventLog.setName(getBedName(eventData.getBedId()));
//        eventLog.setUserId(eventData.getUserId());
//        eventLog.setEventId(eventData.getEventId());
//        eventLog.setType(EventEnum.EVENT_PROC_TAKE.getCode());
//        eventLog.setTypeGroup(EventEnum.EVENT_PROC_TAKE.getType());
//        eventLog.setContent(String.format(EventEnum.EVENT_PROC_TAKE.getContent(), getNurseName(eventData.getUserId())));
//        eventLog.setCreateTime(LocalDateTime.now());
//        eventLog.setTenantId(eventData.getTenantId());
//        this.save(eventLog);
//        return eventLog;
//    }

    private String getBedName(Integer bedId) {
        BedBO bedFullName = bedService.getBedFullName(bedId);
        String name = "";
        if (bedFullName != null) {
            name = bedFullName.getBuildingName() + "-" + bedFullName.getFloorName() + "-" + bedFullName.getRoomName()
                    + "-" + bedFullName.getBedName();
        }
        return name;
    }

    private String getNurseName(Long userId) {
        User user = userManager.getUserById(userId);
        String name = "";
        if (user != null) {
            name = user.getName();
        }
        return name;
    }

    /**
     * 获取事件持续时间
     *
     * @param eventId
     * @return
     */
    private Integer getEventDuration(Long eventId) {
        Integer duration = null;
        Event event = eventService.getById(eventId);
        if (event != null) {
            long happenTime = event.getHappenTime().toEpochSecond(ZoneOffset.of("+8"));
            duration = (int) (System.currentTimeMillis() / 1000 - happenTime);
        }
        return duration;
    }

    private String getCurMonitorTime(Integer bedId) {
        String ret = "";
        try {
            BedMonitorTimeVO bedCurMonitorTime = bedService.getBedCurMonitorTime(bedId);
            if (bedCurMonitorTime != null) {
                ret = bedCurMonitorTime.getStartTime() + "-" + bedCurMonitorTime.getEndTime();
            }
        } catch (Exception e) {
            log.error("getCurMonitorTime error", e);
        }
        return ret;
    }

    /**
     * 实时监控页面 获取指定床位事件信息列表(最新和更多)
     *
     * @param param
     * @return
     */
    @Override
    public List<EventLogVO> getBedEventList(BedEventParam param) {
        Long lastId = param.getLastId();
        List<EventLog> eventLogs = this.getBaseMapper().selectList(Wrappers.<EventLog>lambdaQuery()
                .eq(EventLog::getBedId, param.getBedId()).lt(lastId != 0, EventLog::getId, lastId)
                .orderByDesc(EventLog::getId).last("limit " + param.getSize()));
        List<EventLogVO> eventLogVOS = eventLogs.stream().map(eventLog -> {
            EventLogVO eventLogVO = new EventLogVO();
            eventLogVO.setName(eventLog.getName());
            eventLogVO.setEvtLogId(eventLog.getId());
            eventLogVO.setContent(eventLog.getContent());
            eventLogVO.setTime(DateUtil.formatFullTime(eventLog.getCreateTime(), DateUtil.FULL_TIME_CHS_PATTERN));
            if (eventLog.getTypeGroup() == EventEnum.TYPE_ALARM) {
                // 报警
                eventLogVO.setIsAlarm(1);
            }
            return eventLogVO;
        }).collect(Collectors.toList());

        return eventLogVOS;
    }

    @Override
    public CommonRes<List<EventLogVO>> getAllEvent(AllEventParam param) {
        Long lastId = param.getLastId();
        List<EventLog> eventLogs = this.getBaseMapper().selectList(Wrappers.<EventLog>lambdaQuery()
                .lt(lastId != 0, EventLog::getId, lastId)
                .orderByDesc(EventLog::getId).last("limit " + param.getSize()));
        List<EventLogVO> eventLogVOS = eventLogs.stream().map(eventLog -> {
            EventLogVO eventLogVO = new EventLogVO();
            eventLogVO.setName(eventLog.getName());
            eventLogVO.setEvtLogId(eventLog.getId());
            eventLogVO.setContent(eventLog.getContent());
            eventLogVO.setTime(DateUtil.formatFullTime(eventLog.getCreateTime(), DateUtil.FULL_TIME_CHS_PATTERN));
            if (eventLog.getTypeGroup() == EventEnum.TYPE_ALARM) {
                // 报警
                eventLogVO.setIsAlarm(1);
            }
            return eventLogVO;
        }).collect(Collectors.toList());

        return CommonRes.ok(eventLogVOS);
    }

    /**
     * 院长首页 查询事件信息列表（查看更多）
     *
     * @param param
     * @return
     */
    @Override
    public IPage<EventLogVO> searchEvent(SearchEventParam param, PageParam pageParam) {
        // 处理事件类型筛选项
        Set<Integer> typeBedIds = new HashSet<>();
        Set<Integer> typeNurseIds = new HashSet<>();
        boolean isAllType = false;
        if (StringUtils.isNotEmpty(param.getTypeIds())) {
            if (param.getTypeIds().equals("0")) {
                // 事件类型未选中
                return new Page<>();
            } else {
                // 事件类型选择个别
                List<Integer> listFilter = Arrays.stream(param.getTypeIds().split(","))
                        .map(Integer::valueOf).collect(Collectors.toList());
                for (Integer filterType : listFilter) {
                    DictBO dict = dictManager.getDictItem(EventServiceImpl.DICT_EVENT_FILTER_TYPE, (long) filterType);
                    if (dict != null) {
                        List<Integer> eventTypeIds = JsonUtils.jsonToList(dict.getOtherVal(), Integer.class);
                        if (CollectionUtils.isNotEmpty(eventTypeIds)) {
                            if (filterType == EventServiceImpl.EVENT_FILTER_TYPE_TOUR
                                    || filterType == EventServiceImpl.EVENT_FILTER_TYPE_CHANGE_SHIFTS) {
                                // 巡视或者交接班
                                typeNurseIds.addAll(eventTypeIds);
                            } else {
                                // 床位相关
                                typeBedIds.addAll(eventTypeIds);
                            }
                        }
                    }
                }
            }
        } else {
            // 全部事件类型
            isAllType = true;
        }

        Set<Integer> allNurseType = new HashSet<>();
        DictBO dictTour = dictManager.getDictItem(EventServiceImpl.DICT_EVENT_FILTER_TYPE, (long) EventServiceImpl.EVENT_FILTER_TYPE_TOUR);
        if (dictTour != null) {
            List<Integer> eventTypeIds = JsonUtils.jsonToList(dictTour.getOtherVal(), Integer.class);
            if (CollectionUtils.isNotEmpty(eventTypeIds)) {
                allNurseType.addAll(eventTypeIds);
            }
        }
        DictBO dictChange = dictManager.getDictItem(EventServiceImpl.DICT_EVENT_FILTER_TYPE, (long) EventServiceImpl.EVENT_FILTER_TYPE_CHANGE_SHIFTS);
        if (dictChange != null) {
            List<Integer> eventTypeIds = JsonUtils.jsonToList(dictChange.getOtherVal(), Integer.class);
            if (CollectionUtils.isNotEmpty(eventTypeIds)) {
                allNurseType.addAll(eventTypeIds);
            }
        }
        // 处理床位筛选项
        Set<Integer> bedIds = null;
        boolean isAllBed = false;
        boolean isNoBed = false;
        if (StringUtils.isNotEmpty(param.getBedIds())) {
            if (param.getBedIds().equals("0")) {
                // 床位未选中
                isNoBed = true;
            } else {
                // 床位选择部分
                bedIds = Arrays.stream(param.getBedIds().split(",")).map(Integer::valueOf).collect(Collectors.toSet());
            }
        } else {
            isAllBed = true;
            User currentUser = RecoupUtil.getCurrentUser();
            Long userId = currentUser.getId();
            Integer roleId = Integer.parseInt(currentUser.getRoleId());
            List<Integer> bedIdsByUser = bedService.getBedIdsByUser(userId, roleId);
            if (CollectionUtils.isEmpty(bedIdsByUser) || bedIdsByUser.get(0) == 0) {
                return new Page<>();
            }
            // 设置床位条件
            if (bedIdsByUser.get(0) != -1) {
                bedIds = new HashSet<>(bedIdsByUser);
            }
        }
        // 时间和排序条件
        LocalDate startDate = LocalDate.parse(param.getStartDate());
        LocalDate endDate = LocalDate.parse(param.getEndDate()).plusDays(1);
        LambdaQueryWrapper<EventLog> wrapper = Wrappers.lambdaQuery();
        wrapper.between(EventLog::getCreateTime, startDate, endDate).orderByDesc(EventLog::getId);
        if (isAllBed) {
            // 全部床位
            if (isAllType) {
                // 全部事件，只按时间查询
            } else {
                // 部分事件
                Set<Integer> allType = new HashSet<>(typeBedIds);
                allType.addAll(typeNurseIds);
                wrapper.in(EventLog::getType, allType);
            }
        } else if (isNoBed) {
            // 未选中床位
            if (isAllType) {
                // 全部事件
                wrapper.in(EventLog::getType, allNurseType);
            } else if (CollectionUtils.isNotEmpty(typeNurseIds)) {
                // 存在护工相关事件
                wrapper.in(EventLog::getType, typeNurseIds);
            } else {
                // 无结果
                return new Page<>();
            }
        } else {
            final Set<Integer> bedIdsTmp = bedIds;
            // 部分床位
            if (isAllType) {
                // 全部事件
                if (param.getOnlyBed() != null && param.getOnlyBed() == 1) {
                    wrapper.in(EventLog::getBedId, bedIdsTmp);
                } else {
                    wrapper.and(i -> i.in(EventLog::getBedId, bedIdsTmp)
                            .or(j -> j.in(EventLog::getType, allNurseType)));
                }
            } else {
                // 部分事件
                wrapper.and(i -> i.in(EventLog::getBedId, bedIdsTmp)
                        .in(CollectionUtils.isNotEmpty(typeBedIds), EventLog::getType, typeBedIds)
                        .or(CollectionUtils.isNotEmpty(typeNurseIds), j -> j.in(EventLog::getType, typeNurseIds)));
            }
        }

        Page<EventLog> eventLogPage = new Page<>();
        eventLogPage.setCurrent(pageParam.getPageNum());
        eventLogPage.setSize(pageParam.getPageSize());
        IPage<EventLog> eventLogIPage = this.getBaseMapper().selectPage(eventLogPage, wrapper);
        List<EventLog> eventLogs = eventLogIPage.getRecords();
        List<EventLogVO> eventLogVOS = eventLogs.stream().map(eventLog -> {
            EventLogVO eventLogVO = new EventLogVO();
            eventLogVO.setName(eventLog.getName());
            eventLogVO.setEvtLogId(eventLog.getId());
            eventLogVO.setContent(eventLog.getContent());
            eventLogVO.setTime(DateUtil.formatFullTime(eventLog.getCreateTime(), DateUtil.FULL_TIME_CHS_PATTERN));
            // 设置是否报警
            if (eventLog.getTypeGroup() == EventEnum.TYPE_ALARM) {
                eventLogVO.setIsAlarm(1);
            }
            // 设置是否突出显示
            Integer type = eventLog.getType();
            EventEnum eventEnum = EventEnum.getByCode(type);
            if(eventEnum!=null){
                boolean  isStress =  eventEnum.isStress();
                if (isStress) {
                    eventLogVO.setIsStress(1);
                }
            }
            return eventLogVO;
        }).collect(Collectors.toList());
        Page<EventLogVO> eventLogVOPage = new Page<>();
        eventLogVOPage.setTotal(eventLogIPage.getTotal());
        eventLogVOPage.setSize(eventLogIPage.getSize());
        eventLogVOPage.setCurrent(eventLogIPage.getCurrent());
        eventLogVOPage.setRecords(eventLogVOS);
        return eventLogVOPage;
    }

    @Override
    public EventLogData4NurseBO getNurseStatisticsDataByDay(Long userId, LocalDate day) {
        Integer missedNum = this.baseMapper.selectCount(Wrappers.<EventLog>lambdaQuery()
                .eq(EventLog::getUserId, userId)
                .eq(EventLog::getType, EventEnum.EVENT_PROC_HAPPEN_MISSED_EVENT.getCode())
                .between(EventLog::getCreateTime, day, day.plusDays(1)));
        EventLogData4NurseBO eventLogData4NurseBO = new EventLogData4NurseBO();
        eventLogData4NurseBO.setMissedEventNum(missedNum);
        return eventLogData4NurseBO;
    }

    @Override
    public EventLog getLastEvent(Integer id) {
        return this.baseMapper.getLastEvent(id);
    }
}
